package cn.felord.core.controller;


import cn.felord.core.controller.base.SuperController;
import cn.felord.core.entity.SysUser;
import cn.felord.core.mongo.bean.FileEntity;
import cn.felord.core.mongo.dao.FileEntityDao;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传控制器
 * Created by Gaojun.Zhou 2017年4月28日
 */

@Controller
public class FileUploadController extends SuperController {

    public static final Logger logger = Logger.getLogger(FileUploadController.class);
    @Resource
    private FileEntityDao fileEntityDao;

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/file/upload")
    public Map<String, Object> fileUpload(@RequestParam MultipartFile file) {
        SysUser current=this.getCurrentUser();
        System.out.println(current);
        Map<String, Object> result = new HashMap<>();
        List<FileEntity> fileEntities = new ArrayList<>();
        try {

            if (file.isEmpty()) {
                logger.warn("文件未上传");
            } else {
                String originalFilename = file.getOriginalFilename();
                byte[] data = file.getBytes();
                String contentType = file.getContentType();
                String name = file.getName();
                long crtTime = System.currentTimeMillis();

                FileEntity fileEntity = new FileEntity();
                fileEntity.setOriginalFilename(originalFilename);
                fileEntity.setContentType(contentType);
                fileEntity.setData(data);
                fileEntity.setName(name);
                fileEntity.setCrtTime(crtTime);
                fileEntities.add(fileEntity);
            }

            if (CollectionUtils.isNotEmpty(fileEntities)) {
                fileEntityDao.saveBatch(fileEntities);
            }

            result.put("status", "success");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("status", "error");
            return result;
        }
    }
    @RequestMapping("/file/read")
    public void read(@RequestParam String name, HttpServletResponse response) throws IOException {
        FileEntity fileEntity = fileEntityDao.findOne(name);
        response.getOutputStream().write(fileEntity.getData());
    }
}
